package middlewares

import (
	"net/http"

	"gitee.com/lflxp/dogo"
	. "gitee.com/lflxp/dogo/model/admin"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
)

func helloHandler(c *gin.Context) {
	claims := jwt.ExtractClaims(c)
	user, _ := c.Get(identityKey)
	c.JSON(200, gin.H{
		"userID":   claims[identityKey],
		"userName": user.(*User).Username,
		"text":     "Hello World.",
		"claims":   claims["userClaims"],
	})
}

// 注册auth
func RegisterJWT() {
	apiGroup := dogo.NewRails().Group("/auth")
	// login
	apiGroup.POST("/login", Login)
	apiGroup.GET("/logout", Logout)

	var authMiddleware = NewGinJwtMiddlewares(AllUserAuthorizator)
	authGroup := dogo.NewRails().Group("/auth")
	authGroup.Use(authMiddleware.MiddlewareFunc())
	{
		// Refresh time can be longer than token timeout
		authGroup.GET("/refreshtoken", RefreshToken)
		authGroup.GET("/hello", helloHandler)
	}
}

// @Summary  通用接口
// @Description 登陆、swagger、注销、404等
// @Tags Auth
// @Param token query string false "token"
// @Param data body User true "data"
// @Success 200 {string} string "success"
// @Security ApiKeyAuth
// @Router /auth/login [post]
func Login(c *gin.Context) {
	var authMiddleware = NewGinJwtMiddlewares(AllUserAuthorizator)
	authMiddleware.LoginHandler(c)
}

// @Summary  通用接口
// @Description 登陆、swagger、注销、404等
// @Tags Auth
// @Success 200 {string} string "success"
// @Security ApiKeyAuth
// @Router /auth/logout [get]
func Logout(c *gin.Context) {
	var authMiddleware = NewGinJwtMiddlewares(AllUserAuthorizator)
	authMiddleware.LogoutHandler(c)
	c.Redirect(http.StatusFound, "/login")
}

// @Summary  通用接口
// @Description 登陆、swagger、注销、404等
// @Tags Auth
// @Success 200 {string} string "success"
// @Security ApiKeyAuth
// @Router /auth/refreshtoken [get]
func RefreshToken(c *gin.Context) {
	var authMiddleware = NewGinJwtMiddlewares(AllUserAuthorizator)
	authMiddleware.RefreshHandler(c)
}
